package com.xmx.authcenter.controller;


import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.common.utils.IPUtil;
import com.nimbusds.jose.JWSObject;
import com.xmx.authcenter.constant.MessageConstant;
import com.xmx.authcenter.constant.RedisConstant;
import com.xmx.authcenter.dto.MemberDto;
import com.xmx.authcenter.dto.UserInfo;
import com.xmx.authcenter.feign.MemeberFeignClient;
import com.xmx.authcenter.service.ResourceServiceImpl;
import com.xmx.common.config.WxResponseCode;
import com.xmx.common.utils.IPUtils;
import com.xmx.common.utils.R;
import lombok.extern.slf4j.Slf4j;

import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import sun.security.acl.PrincipalImpl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/oauth")
@Slf4j
public class AuthController {

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private TokenEndpoint tokenEndpoint;


    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public R postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {

        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();

        return R.ok().put("token",oAuth2AccessToken.getValue()).put("refresh_token",oAuth2AccessToken.getRefreshToken().getValue());
    }



    @PostMapping("/logout")
    public R logout(HttpServletRequest request) throws ParseException {
        String token = request.getHeader("Authorization");
        token = token.replace("Bearer", Strings.EMPTY);
        JWSObject jwsObject = JWSObject.parse(token);
        String payload = jwsObject.getPayload().toString();
        JSONObject jsonObject = JSONUtil.parseObj(payload);
        String jti = jsonObject.getStr("jti"); // JWT唯一标识
        long exp = jsonObject.getLong("exp"); // JWT过期时间戳(单位:秒)

        long currentTimeSeconds = System.currentTimeMillis() / 1000;

        if (exp < currentTimeSeconds) { // token已过期
            return R.error(MessageConstant.CREDENTIALS_EXPIRED);
        }
        redisTemplate.opsForValue().set(RedisConstant.TOKEN_BLACKLIST_PREFIX + jti, null, (exp - currentTimeSeconds), TimeUnit.SECONDS);
        return R.ok("退出成功");
    }




}
